/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package guzik.lukasz.snpexplorer;

import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragGestureRecognizer;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author Łukasz 'byku' Guzik
 */
public class TreeDragSource implements DragSourceListener, DragGestureListener
{
    private DragSource source;
    private DragGestureRecognizer recognizer;
    private TransferableTreeNode transferable;
    private JTree sourceTree;
    private TreePath path;

    public TreeDragSource(JTree sourceTree)
    {
	this.sourceTree = sourceTree;
	source = new DragSource();
	recognizer = source.createDefaultDragGestureRecognizer(sourceTree,
		DnDConstants.ACTION_MOVE, this);
    }

    @Override
    public void dragEnter(DragSourceDragEvent dsde)
    {
    }

    @Override
    public void dragOver(DragSourceDragEvent dsde)
    {
    }

    @Override
    public void dropActionChanged(DragSourceDragEvent dsde)
    {
    }

    @Override
    public void dragExit(DragSourceEvent dse)
    {
    }

    @Override
    public void dragDropEnd(DragSourceDropEvent dsde)
    {
	DefaultMutableTreeNode node;
	if(dsde.getDropSuccess() && path != null)
	{
	    node = (DefaultMutableTreeNode)path.getLastPathComponent();
	    ((DefaultTreeModel)sourceTree.getModel()).removeNodeFromParent(node);
	}
    }

    @Override
    public void dragGestureRecognized(DragGestureEvent dge)
    {
	path = sourceTree.getSelectionPath();
	if(path == null || path.getPathCount() <= 1)
	{
	    return;
	}

	transferable = new TransferableTreeNode(path);
	source.startDrag(dge, DragSource.DefaultMoveDrop, transferable, this);
    }

    public void setEnabled(boolean enabled)
    {
	if(enabled)
	{
	    recognizer.setSourceActions(DnDConstants.ACTION_MOVE);
	}
	else
	{
	    recognizer.setSourceActions(DnDConstants.ACTION_NONE);
	}
    }
}
